<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Service;

use App\Constants\ContentType;
use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\Content;
use App\Schema\ContentListSchema;
use App\Schema\ContentSchema;
use App\Service\Dao\ContentDao;
use App\Service\Dao\SecretDao;
use App\Service\Formatter\ContentFormatter;
use App\Service\SubService\Encrypt;
use App\Service\SubService\UserAuth;
use Hyperf\Di\Annotation\Inject;

class ContentService extends Service
{
    #[Inject]
    protected ContentDao $dao;

    #[Inject]
    protected Encrypt $encrypt;

    #[Inject]
    protected ContentFormatter $formatter;

    public function create(int $id, array $input, UserAuth $userAuth): bool
    {
        $userAuth->build();

        if ($id > 0) {
            $model = $this->dao->first($id, true);
            if ($model->user_id !== $userAuth->getUserId()) {
                throw new BusinessException(ErrorCode::PERMISSION_DENY);
            }
        } else {
            $model = new Content();
            $model->user_id = $userAuth->getUserId();
            $model->secret_id = $input['secret_id'];
        }

        $model->type = ContentType::tryFrom($input['type']);
        $model->title = $input['title'];
        $model->content = $this->encrypt->encrypt($input['content'], $userAuth->getSecret());

        return $model->save();
    }

    public function info(int $id, UserAuth $userAuth): ContentSchema
    {
        $userAuth->build();
        $model = $this->dao->first($id, true);
        if ($model->user_id !== $userAuth->getUserId()) {
            throw new BusinessException(ErrorCode::PERMISSION_DENY);
        }

        return new ContentSchema($model, true);
    }

    public function list($secret_id, UserAuth $userAuth): ContentListSchema
    {
        $userAuth->build();
        $secret = di()->get(SecretDao::class)->first($secret_id, true);
        if ($secret->user_id !== $userAuth->getUserId()) {
            throw new BusinessException(ErrorCode::PARAMS_INVALID);
        }

        $result = $this->dao->selectBySecretId($secret_id);
        $list = $this->formatter->formatterList($result);

        return new ContentListSchema($list, $result->count());
    }
}
